/* Requirements:
*   jQuery
*   underscore.js
*/
var Caldera = (function () {
	var self = {},
	    debug = true,
	    $e = {},
	    $doc = $(document),
	    $body = $('body'),
	    flyout_speed = 200,
	    ajax_urls = {
	        all_series: '/ajax/all-series/',         //json response
	        spas_by_series: '/ajax/spas-by-series/', //json response
	        series_intro: '/ajax/series-intro/',
	        fetch_spa: '/ajax/spa/',
			fetch_spa_compare: '/ajax/spa-data/',	//json response
			all_spas: '/ajax/all-spas/',	//json response
	    },
	    flyout_all_series_loaded = false,
        flyout_series_elements = {};

    /* ============================================================================== */
    /* Helper functions
    /* ============================================================================== */
	function _log(str) {
	    if(debug) console.log(str);
	}

	//Grab the height of the entire document correctly
	function _get_document_height(){
	    var body = document.body,
            html = document.documentElement;
	    return Math.max( body.scrollHeight, body.offsetHeight,
                               html.clientHeight, html.scrollHeight, html.offsetHeight );
	}

	function _get_document_width() {
	    return $doc.width();
	}

	// Set the hight of param:JQobject to document height
	function reset_height($object) {
	    $object.css({height: _get_document_height()+'px'});
	}

    /* ============================================================================== */
    /* Navigation spa model flyout functionality
    /* ============================================================================== */

	function init_flyout() {
	    //set the flyout position
        // var t_offset = $e.flyout_li.offset().top;
        // $e.flyout.css({top: t_offset - 1});
	    set_active_series(false);

	    $e.flyout_anchor.click(function(e){
	        e.preventDefault();
	        open_flyout();

            setTimeout(function() {
                $e.flyout.bind( "clickoutside", function(e){
                    close_flyout();
                });
            }, 100)
	    });

	    $e.flyout_anchor_open.click(function(e){
	        e.preventDefault();
	        close_flyout();
	    });

	    $e.flyout_all_series.find('a').live('click', function(e){
	        e.preventDefault();
	        load_spas_by_series($(this).attr('id').replace('flyout_', ''));
	        remove_all_active();
	        $(this).addClass('active');
	    });

	    $e.flyout_left.fadeTo('slow',0.5).live('click', function(e){
	        e.preventDefault();
	        scroll_active_flyout('left');
	    });

	    $e.flyout_right.live('click', function(e){
	        e.preventDefault();
	        scroll_active_flyout('right');
	    });

	    $e.flyout_close.click(function(e){
	        e.preventDefault();
	        close_flyout();
	    });

        $(window).resize(function(e){
            if(scroll_calculate_in_view()) { $e.flyout_right.fadeTo('fast',0.5); } else {$e.flyout_right.fadeTo('fast',1.0);}
        })
	}

	function open_flyout() {
	    $e.flyout.show().animate({height:'303px'}, flyout_speed, function(){
	        $e.flyout.animate({width:'100%'}, flyout_speed, function(){
	            init_flyout_ajax();
	        });
	    });
	}

	function close_flyout() {
	    $e.flyout.unbind('clickoutside');
        $e.flyout.animate({width:'275px'}, flyout_speed, function(){
	        $e.flyout.animate({height: '0px'}, flyout_speed, function(){
    	        $(this).hide();
	        });
	    });
	}

	function init_flyout_ajax() {
        if(!flyout_all_series_loaded){
            $.getJSON(ajax_urls.all_series, function(data){
                var series_list = '<ul><% _.each(series, function(s)\
                { %><li <% if(_.last(series) == s){%>class="last"<% } %>><a href="" id="flyout_<%= s.slug %>"><%= s.name.replace("®", "<sup>®</sup>") %> Series</a></li><% }); %></ul>';
                var t = _.template(series_list, {series : data});
                $e.flyout_all_series.html(t);
                $e.flyout_all_series.find('a:first').click();
                flyout_all_series_loaded = true;
            });
        }
	}

	function load_spas_by_series(series_slug) {
	    var url = ajax_urls.spas_by_series + series_slug + '/';
        if(!_.has(flyout_series_elements, series_slug) || !flyout_series_elements[series_slug]['loaded']){

            if(get_active_series()){
                flyout_series_elements[get_active_series()]['container'].hide();
            }

            $e.flyout_element_container.append('<div id="'+series_slug+'_element_container"></div>');
            var series_container = $e.flyout_element_container.find('#'+series_slug+'_element_container');

            $.get(ajax_urls.series_intro + series_slug + '/', function(intro){
                hide_all_intros();
                $e.flyout_intro_container.append(intro);
                var series_intro = $e.flyout_intro_container.find('#flyout_intro_'+series_slug);

                $.getJSON(url, function(data){
                    series_container.html(data.rendered.replace("®", "<sup>®</sup>"));
                    set_active_series(series_slug);
                    flyout_series_elements[series_slug] = {loaded: true, container: series_container, click_count: 1, total: data.total, intro: series_intro};
                    setTimeout(function(){
                        reset_scroll();
                    }, 100)
                });

            });
        } else {
            if(get_active_series() != series_slug) {
                flyout_series_elements[get_active_series()]['container'].hide();
                flyout_series_elements[series_slug]['container'].show();
                hide_all_intros();
                flyout_series_elements[series_slug]['intro'].show();
                set_active_series(series_slug);
                reset_scroll();
            }
        }
	}

    function scroll_calculate_in_view() {
        // Check if all the spas are visible
        var active = flyout_series_elements[get_active_series()],
            offset = 300+30+40, // margin-left of #flyout_elements, padding of its parent, arrow right width
            flyout_elements_width = active.container.parents('#flyout_elements').width()-offset,
            spa_number = active.container.find('.flyout_element').length+1

        //console.log(spa_number, active.click_count, (spa_number-active.click_count)*475, flyout_elements_width)

        return (spa_number-active.click_count)*475<flyout_elements_width
    }

	function scroll_active_flyout(direction) {
	    var active = flyout_series_elements[get_active_series()];

        //disable left with under 1 click
        if(active.click_count <= 1 && direction == 'left') { return false; }
        //disable clicking right when at the last element
        if(active.click_count > (active.total - 1) && direction == 'right') { return false; }

        //disable clicking right if all spas are visible
        if (scroll_calculate_in_view() && direction == 'right') { return false }

        var current_offset = parseInt(active.container.css('margin-left').replace('px',''));
        // IE8 returns the intial margin-left as 'auto' resulting in NaN, corrected below
        if (isNaN(current_offset)) { current_offset = 0; }
        var offset = current_offset - 475
        if (direction == 'left') { offset = current_offset + 475;}

        active.container.animate({'margin-left': offset +'px'}, 300, 'swing');

        var new_count = (direction == 'left') ? active.click_count - 1 : active.click_count + 1;
        flyout_series_elements[get_active_series()]['click_count'] = new_count;

        //check where we are, what arrows should fade?
        if((new_count > (active.total - 1)) || scroll_calculate_in_view()) { $e.flyout_right.fadeTo('slow',0.5); } else {$e.flyout_right.fadeTo('slow',1.0);}
        if(new_count <= 1) { $e.flyout_left.fadeTo('slow',0.5); } else {$e.flyout_left.fadeTo('slow',1.0);}
	}

    function reset_scroll() {
        flyout_series_elements[get_active_series()]['click_count'] = 1;
        flyout_series_elements[get_active_series()]['container'].animate({'margin-left': '0'});
        $e.flyout_left.fadeTo('slow',0.5); $e.flyout_right.fadeTo('slow',1.0);
    }
    function hide_all_intros() { $e.flyout.find('.flyout_intro').hide(); }
    function remove_all_active() { $e.flyout_all_series.find('a').removeClass('active');}
	function set_active_series(value) { $body.data('flyout_active_series', value); }
	function get_active_series() { return $body.data('flyout_active_series'); }

	//hack footer to move to the bottom
	function reset_footer(hard_value) {
        return false;
        // if(hard_value) {
        //     var height = hard_value;
        // } else {
        //     var height = _get_document_height() + 150;
        // }
        // if(!$body.hasClass('homepage')) $e.footer.css('top', height);
	}

    function eventTracking() {
        var debug_events = false

        var textcontents = function($el) {
            return $.trim($el.text())
        }

        var trackIt = function() {
            var li = Array.prototype.slice.call(arguments, 0);
            li.unshift('_trackEvent')

            if (debug_events) {
                console.log(li)
                return false
            }

            _gaq.push(li);

            // allow google script to run
            var date = new Date();
            var curDate = null;
            do {
                curDate = new Date();
            } while(curDate-date < 300);

            return true
        }

        // Track PDFs
        $('a[class*="pdf"]').click(function(e) {
            return trackIt('downloads', 'pdf', textcontents($(this)) + ' ' + $(this).attr('href'));
        })

        // Track CADs
        $('a[class*="zip"]').click(function(e) {
            return trackIt('downloads', 'non-pdf', textcontents($(this)) + ' ' + $(this).attr('href'));
        })

        // HTCT Videos
        setTimeout(function() {
            $('.station-jets-video a').on('click', function(e){
                return trackIt('circuit therapy', 'click', textcontents($('.htct-station h3')))
            })
        }, 1000)

        // Social links in side nav
        $('#nav_col #social_links a').click(function(e) {
            return trackIt('sidenav', 'click', $(this).attr('title'))
        })

        // Country Selector links
        $('#country_selector_content a').on('click', function(e) {
            return trackIt('site top nav', 'click', 'Country Selector - '+textcontents($(this)))
        })

        // Owners Corner
        $('#owners_corner a').click(function(e) {
            return trackIt('site top nav', 'click', 'Owners Corner')
        })

        // Find a dealer
        $('#find_dealer a').click(function(e){
            return trackIt('site top nav', 'click', 'Find a Dealer Go')
        })

        // Homepage CTA's
        $('#cta_block .cta a').click(function(e) {
            return trackIt('homepage cta', 'click', textcontents($(this).parents('.cta').find('h2')))
        })

        // Subnav CTA's
        $('.sub-nav.right a').click(function(e){
            return trackIt('CTA Bar', 'click', textcontents($(this)))
        })

        // Find a dealer search clicked
        $('.dealer-locator-box.form-search input[type="image"]').click(function(e){
            return trackIt('find a dealer', 'click', 'search button '+$('#id_postal_code').val())
        })

        // Renewal Blog Slider
        $('.blog_page .carousel a').click(function(e){
             return trackIt('Blog Sliders', 'click', textcontents($(this).parents('.item').find('h2')))
        })

        // Pure X pages
        $('.parent_caldera-difference a[rel="lightbox"]').click(function(e){
            try {
                var name = $('body').attr('class').match(/pure-(.*)?/)[0]
            } catch(e) {
                var name = 'caldera difference'
            }
            return trackIt(name, 'click', $(this).attr('title') + ' Video')
        })

    }

    /* ============================================================================== */
    /* Caldera JS initialization
    /* ============================================================================== */
	self.init = function () {

	    //Cache DOM objects
        $e.leftnav = $('#nav_col'),
        $e.hero = $('#hero'),
        $e.search = $('#country_search'),
        $e.main_col = $('#main_col'),
        $e.flyout_li = $('#flyout_li'),
        $e.flyout_anchor = $('#main_nav_shop a'),
        $e.flyout_anchor_open = $('#flyout_anchor_open'),
        $e.flyout_top = $('#flyout_top'),
        $e.flyout = $('#flyout'),
        $e.flyout_content = $('#flyout_content'),
        $e.flyout_close = $('#flyout_close'),
        $e.flyout_all_series = $('#flyout_all_series'),
        $e.flyout_element_container = $('#flyout_elements'),
        $e.flyout_intro_container = $('#flyout_series_intro'),
        $e.flyout_left = $('#flyout_left'),
        $e.flyout_right = $('#flyout_right'),
        $e.footer = $('footer'),
        $e.global_hub = $('#global-hub');

        //add some jiggly registration action:
        // -------------------------
    	// Product registration link
    	// -------------------------
        /*
    	$('a.registration').click(function(e) {
            e.preventDefault();
    	    $.fancybox({
        	    'type'  : 'iframe',
        	    'href'  : '/register-product',
        	    'showCloseButton' : false,
        	    'width' : 600,
        	    'height' : 680

        	});
    	});
        */


    	//'/sites/default/files/static/product-registration.html'


        // set footer to bottom
        // TODO: Test & figure out why some pages fail. Floats not in doc height calculation?
        //_log(_get_document_height() + 150);


        //init model flyout, unless we're coming from mobile...
        if (!$.cookie('ref_from_mobile')) {
            init_flyout();
        }
        //$(window).resize(function(){
        //    reset_height($e.leftnav);
        //});

        //set the initial height of the left navbar
        //var computed_height = $e.main_col.height() + $e.main_col.offset().top
        //var initial_nav_height = computed_height > 1000 ? computed_height : 1000;
        //$e.leftnav.css('height', initial_nav_height+'px');

        //init the carousel:
        $('.carousel').carousel({
          interval: 6000,
          pause: 'hover'
        })

            // country selector
            // ---------------
        	// Global Hub Page
        	// ---------------
            $('#country_selector > a').click(function(e){ e.preventDefault(); });
        	$('#country_selector > a').hover(
        		function() {
                    $('.insert-nid405').slideDown(350);
                    $('#country_selector').addClass('active');
                },
        		function() { return false; }
        	);

                    $('.insert-nid405').mouseleave(function(){
                        $('.insert-nid405').slideUp(350, function() {
                            $('#country_selector').removeClass('active');
                        });
                    });

                      $('.americas-map, .europe-map, .africa-map, .asia-pacific-map').mouseover(function() {
                          // Switch which map is active
                          $e.global_hub.find('.americas-map, .europe-map, .africa-map, .asia-pacific-map').removeClass('current-map');
                            var cur_class = $(this).attr('class');
                            var set_id;
                            switch(cur_class) { case "americas-map": set_id='america';break; case "europe-map": set_id="europe";break; case "africa-map": set_id="africa";break; case "asia-pacific-map": set_id="asia";break;}
                            $(this).parent().attr('id', set_id);

                          $(this).addClass('current-map');

                          $e.global_hub.find('.americas-links, .europe-links, .africa-links, .asia-pacific-links').hide();
                          if ($(this).hasClass('americas-map')) $(this).closest('.global-hub').find('.americas-links').show();
                          if ($(this).hasClass('europe-map')) $(this).closest('.global-hub').find('.europe-links').show();
                          if ($(this).hasClass('africa-map')) $(this).closest('.global-hub').find('.africa-links').show();
                          if ($(this).hasClass('asia-pacific-map')) $(this).closest('.global-hub').find('.asia-pacific-links').show();
                      });

        // language selector
        $('#language_selector a').hover(
            function() { $('#language_select').slideDown(350); },
            function() { return false; }
        );
        $('#language_select').mouseleave(function(){$(this).slideUp(350);});

        // If we're coming from mobile, provide a link back...
        if ($.cookie('ref_from_mobile')) {
            var flavor = $.cookie('ref_from_mobile').toLowerCase().replace(/\b[a-z]/g, function(letter) {
                return letter.toUpperCase();
            })
            $('<div class="view-mobile-site"><a href="/?flavor='+flavor.toLowerCase()+'">View '+flavor+' Site</a></div>').appendTo('body')

            // Also add some classes to the html
            jQuery('html').addClass('full-from-handheld flavor-'+flavor.toLowerCase())
        }

        // Fix placeholders for IE
        $(':text').placeholderFix();

        //toggle the CTAs on the homepage

        $("#toggleDiscover").toggle(function() {
        	$("#toggleDiscover").toggleClass("discoverExpand", 1000);
        	$(".cta").animate({
        		opacity: 0
        		}, 200);
        	$("#cta_block").animate({
        		//width: 'toggle',
        		height: 'toggle',
        		opacity: 0
        		}, 500);

        }, function() {
        	$("#toggleDiscover").toggleClass("discoverExpand", 1000);
        	$(".cta").animate({
        		opacity: 1
        		}, 200);
        	$("#cta_block").animate({
        		//width: 'toggle',
        		height: 'toggle',
        		opacity: 1
        		}, 500);
        });

        // Wire up our event tracking
        eventTracking()
	}

	//make height function public for testing via console
	//self._debug_height = _get_document_height;
	//self._debug_width = _get_document_width;
	self.reset_footer = reset_footer;
	//self._flyout_series_elements = flyout_series_elements;

	return self;
}());